/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: HomeTradeFragment.java
 *   @Date: 1/10/19 2:08 PM
 *   @Author: chenjun
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.app.trade.ui;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;

import java.util.ArrayList;

import io.bhex.app.R;
import io.bhex.app.base.BaseFragment;
import io.bhex.app.market.adapter.FragmentAdapter;
import io.bhex.app.otc.ui.OtcFragment;
import io.bhex.app.trade.presenter.HomeTradeFragmentPresenter;
import io.bhex.app.utils.BasicFunctionsUtil;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.view.NoScrollViewPager;
import io.bhex.baselib.constant.AppData;
import io.bhex.sdk.config.bean.BasicFunctionsConfig;
import io.bhex.sdk.quote.bean.CoinPairBean;

public class HomeTradeFragment extends BaseFragment<HomeTradeFragmentPresenter,HomeTradeFragmentPresenter.HomeTradeUI> implements HomeTradeFragmentPresenter.HomeTradeUI {

    public static final int TAB_TRADE = 0;
    public static final int TAB_OTC = 1;
    private NoScrollViewPager viewPager;
    private SegmentTabLayout tab;
    private View tabline;
    private ArrayList<Pair<String, Fragment>> items;
    private FragmentAdapter marketAdapter;
    private int mCurrentIndex = 0;
    private CoinPairBean coinPairBean;
    TradeFragment tradeFragment;
    OptionTradeFragment optionTradeFragment;
    private boolean isVisible;
    private BasicFunctionsConfig basicFunctionsConfig;
    private Pair<String, Fragment> tradeFragmentPair;
    private Pair<String, Fragment> otcFragmentPair;
    private int currentTabType=-1;

    @Override
    protected HomeTradeFragmentPresenter.HomeTradeUI getUI() {
        return this;
    }

    @Override
    protected HomeTradeFragmentPresenter createPresenter() {
        return new HomeTradeFragmentPresenter();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home_trade_layout, null, false);
    }

    @Override
    protected void initViews() {
        super.initViews();
        basicFunctionsConfig = BasicFunctionsUtil.getBasicFunctionsConfig();
        viewPager = viewFinder.find(R.id.viewPager);
        viewPager.setScanScroll(false);
        tab = viewFinder.find(R.id.tab);
        tabline = viewFinder.find(R.id.tabline);
        Bundle bundle = getArguments();
        if (bundle != null) {
            coinPairBean = (CoinPairBean) bundle.getSerializable(AppData.INTENT.SYMBOLS);

        }
        initFragmentTab();
    }

    private void initFragmentTab() {

        if (items != null) {
            items.clear();
        }
        ArrayList<String> titles = new ArrayList<String>();
        ArrayList<Fragment> fragments = new ArrayList<Fragment>();
        items = new ArrayList<>();
        if (!basicFunctionsConfig.isExchange()) {
            //币币交易
            tradeFragment = new TradeFragment();
            tradeFragmentPair = new Pair<String, Fragment>(getString(R.string.string_trade_bb),tradeFragment);
            if(coinPairBean != null && coinPairBean.baseTokenOption == null)
                tradeFragment.setDefalutCoinPair(coinPairBean);
            tradeFragment.setHomeControl(new HomeTradeControl() {
                @Override
                public void OnShowTab(boolean bShow) {
                    if(bShow == true)
                        ShowTab();
                    else
                        HideTab();
                }
                @Override
                public boolean IsSelected() {
//                    if(isVisible && viewPager.getCurrentItem() == 0)
//                    return isVisible && viewPager.getCurrentItem() == items.indexOf(tradeFragmentPair);
                    return viewPager.getCurrentItem() == items.indexOf(tradeFragmentPair);
                }
            });
            items.add(tradeFragmentPair);
        }

        if (!basicFunctionsConfig.isOtc()) {
            //OTC
            final OtcFragment otcFragment = new OtcFragment();
            otcFragmentPair = new Pair<String, Fragment>(getString(R.string.string_trade_otc),otcFragment);
            otcFragment.setHomeControl(new HomeTradeControl() {
                @Override
                public void OnShowTab(boolean bShow) {
                    if (bShow) {
                        ShowTab();
                    }else{
                        HideTab();
                    }
                }

                @Override
                public boolean IsSelected() {
//                    return isVisible && viewPager.getCurrentItem() == items.indexOf(otcFragmentPair);
                    return viewPager.getCurrentItem() == items.indexOf(otcFragmentPair);
                }
            });
            items.add(otcFragmentPair);
        }

        if (items.size()>1) {
            tab.setVisibility(View.VISIBLE);
            tabline.setVisibility(View.VISIBLE);
        }else{
            tab.setVisibility(View.GONE);
            tabline.setVisibility(View.GONE);
        }

        marketAdapter = new FragmentAdapter(getChildFragmentManager(),items);
        viewPager.setAdapter(marketAdapter);
//        viewPager.setOffscreenPageLimit(3);
//        tab.setupWithViewPager(viewPager);
//        tab.setTabMode(TabLayout.MODE_FIXED);
//        tab.setTabGravity(TabLayout.GRAVITY_FILL);
//        CommonUtil.setUpIndicatorWidthByReflex2(tab,5,5);

        /** 处理titles *******/
        for (Pair<String, Fragment> item : items) {
            titles.add(item.first);
            fragments.add(item.second);
        }
        String[] strArray = new String[titles.size()];
        String[] titlesArray = titles.toArray(strArray);
        tab.setTabData(titlesArray);
        tab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewPager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setArgumentsOfPageSelect(position);
                tab.setCurrentTab(position);
                if(tradeFragment != null && position == items.indexOf(tradeFragmentPair)) {
                    tradeFragment.getTicker();
                    tradeFragment.requestDepthData();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        if (currentTabType!=-1) {
            if (items != null) {
                switch (currentTabType){
                    case TAB_TRADE:
                        mCurrentIndex = items.indexOf(tradeFragmentPair);
                        break;
                    case TAB_OTC:
                        mCurrentIndex = items.indexOf(otcFragmentPair);
                        break;
                }
            }
        }
        setArgumentsOfPageSelect(mCurrentIndex);
        viewPager.setCurrentItem(mCurrentIndex);

    }

    @Override
    public void onResume() {
        super.onResume();
        tab.setTextSelectColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.white));
    }

    /**
     * 记录当前选择的page tab
     * @param position
     */
    private void setArgumentsOfPageSelect(int position) {
        //设置选中参数
        try{
            if (items != null) {
                for (int i = 0; i < items.size(); i++) {
                    Pair<String, Fragment> pair = items.get(i);
                    if (pair != null) {
                        Fragment secondFragment = pair.second;
                        if (secondFragment != null) {
                            Bundle bundle = new Bundle();
                            if (position == i) {
                                bundle.putBoolean("isSelect",true);
                            }else{
                                bundle.putBoolean("isSelect",false);
                            }
                            secondFragment.setArguments(bundle);
                        }
                    }
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void SetTab(int tabType){
        int item =0;
        currentTabType = tabType;
        if (items != null) {
            switch (tabType){
                case TAB_TRADE:
                    item = items.indexOf(tradeFragmentPair);
                    break;
                case TAB_OTC:
                    item = items.indexOf(otcFragmentPair);
                    break;
            }
        }
        if(tab != null && item < tab.getTabCount()){
            viewPager.setCurrentItem(item);
        }
        mCurrentIndex = item;
    }

    public void ShowTab(){
        tab.setVisibility(View.VISIBLE);
        tabline.setVisibility(View.VISIBLE);
    }

    public void HideTab(){
        tab.setVisibility(View.GONE);
        tabline.setVisibility(View.GONE);
    }


    @Override
    public void onPause() {
        super.onPause();
        //QuoteApi.UnSubTickers();
        //QuoteApi.UnSubDepthData();
    }


    @Override
    public void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        isVisible = visible;
        if (isVisible ) {
            if(tradeFragment != null && viewPager.getCurrentItem() == items.indexOf(tradeFragmentPair)) {
                tradeFragment.getTicker();
                tradeFragment.requestDepthData();
            }
        }else{
            //QuoteApi.UnSubTickers();
            //QuoteApi.UnSubDepthData();
        }
    }
}
